package com.mars.activemq.consumer;

import java.io.File;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import com.mars.component.redis.JedisClient;
import com.mars.tukuan.dto.CarCheckVo;
import com.mars.tukuan.dto.CarStateVo;
import com.mars.tukuan.rpc.api.CarCheckService;
import com.mars.tukuan.rpc.api.CarService;
import com.mars.tukuan.rpc.api.CarStateService;
import com.mars.tukuan.rpc.api.CarUserService;
import com.mars.tukuan.utils.file.FileUtil;
import com.mars.tukuan.utils.file.cloud.UploadCloudStroe;
import com.mars.tukuan.utils.file.cloud.UploadResult;

/**
 * 处理地勤用户上传车况信息
 * @author yhaoquan
 *
 */
@Component
public class CarCheckConsumer {
	private static Logger logger = LoggerFactory.getLogger(CarCheckConsumer.class);
	
	@Autowired
	private CarService carService;
	
	@Autowired
	private CarCheckService carCheckService;
	
	@Autowired
	private CarStateService carStateService;
	
	@Autowired
	private CarUserService carUserService;
	
	@Autowired
	private UploadCloudStroe uploadCloudStroe;
	
	@Autowired
	private JedisClient jedisClient ;
	
	/**
	 * 处理前（新伤）
	 * @param carMessage
	 */
	@JmsListener(destination="car.check")
	public void beboreUpload(CarCheckVo carCheckVo) {
		logger.debug("收到MQ异步消息 ，队列名称[car.check]");
		try {
			
			int carCheckId = this.carCheckService.insertHandler(carCheckVo) ;
			
			if(carCheckVo.isWx()) {//无伤
				CarStateVo entity = new CarStateVo() ;
				entity.setCarCheckId((long)carCheckId);
				entity.setIsHarm(2);
				entity.setCarId(carCheckVo.getCarId());
				entity.setBeforeUserId(carCheckVo.getCarUserId());
				entity.setBeforeTime(new Date());
				this.carStateService.insertSelective(entity) ;
			} else {//新伤
				List<CarStateVo> harms = carCheckVo.getHarms() ;
				if(null != harms) {
					for (CarStateVo carStateVo : harms) {
						
						UploadResult result = this.uploadCloudStroe.uploadFile(new File(carStateVo.getBeforeImageUrl())) ;
						if(result.getStatus()) {
							//删除临时目录下的文件
							FileUtil.deleteFile(carStateVo.getBeforeImageUrl());
							
							carStateVo.setBeforeImageUrl(result.getFileUrl());
							carStateVo.setCarCheckId((long)carCheckId);
							carStateVo.setIsHarm(1);
							carStateVo.setFollow(1);
							this.carStateService.insertSelective(carStateVo) ;
							
							//更新车况检查时间
							this.carService.updateCheckTime(carStateVo.getCarId());
							//更新用户的车况见时间
							this.carUserService.updateCheckTime(carStateVo.getCarUserId());
						}
						
						
					}
					
					//删除Redis缓存中的数据
					String key = "car:before_upload:"+carCheckVo.getCarUserId();
					this.jedisClient.del(key) ;
				}
			}
			
		} catch (Exception e) {
			logger.error("车况管理系统-MQ队列消息，处理新伤发生异常：{}", e.getMessage()) ;
		}
	}
	
}
